package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.qurey.RegionQuery;
import cn.wolfcode.wolf2w.repository.RegionRepository;
import cn.wolfcode.wolf2w.service.IRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("regionService")
public class RegionServiceImpl implements IRegionService {
    @Autowired
    private RegionRepository regionRepository;

    @Autowired
    private MongoTemplate template;

    @Override
    public void save(Region region) {
        region.setId(null);
        regionRepository.save(region);
    }

    @Override
    public void update(Region region) {
        regionRepository.save(region);
    }

    @Override
    public void delete(String id) {
        regionRepository.deleteById(id);
    }

    @Override
    public Region get(String id) {
        Region region = regionRepository.findById(id).get();
        return region;
    }

    @Override
    public List<Region> list() {
        return regionRepository.findAll();
    }

    @Override
    public Page<Region> query(RegionQuery qo) {

        Query query = new Query();
        //count:总条数
        long count = template.count(query, Region.class);
        if (count==0){
            return Page.empty();
        }
        //list:当前页条数
        PageRequest pageRequest
                = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        query.with(pageRequest);
        List<Region> list = template.find(query, Region.class);

         return new PageImpl<>(list,pageRequest,count);
    }

    @Override
    public void saveOrUpdate(Region region) {
        if (region.getId()!=null){
            this.update(region);
        }else {
            this.save(region);

        }

    }

    @Override
    public void changeHotValue(int hot, String id) {
        Query query=new Query();

        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.set("ishot", hot);
        template.updateMulti(query,update ,Region.class );
    }

    @Override
    public List<Region> queryHotRegion() {
        //热门状态
        //排序
        return  regionRepository.findByIshotOrderBySequence(Region.STATE_HOT);
    }


}
